//
//  NSString+Validation.m
//  CreditGroup
//
//  Created by ang on 14-4-2.
//  Copyright (c) 2014年 JPlay. All rights reserved.
//

#import "NSString+Validation.h"
#import <CommonCrypto/CommonDigest.h>

@implementation NSString (Validation)

//根据字符串创建set方法
- (SEL)setingToSel{
    NSString *first = [[self substringToIndex:1] uppercaseString]; //转化成大写的
    NSString *end = [self substringFromIndex:1];
    NSString *setSel = [NSString stringWithFormat:@"set%@%@:",first,end];
    return NSSelectorFromString(setSel);
}

//根据字符串创建get方法
- (SEL)getingToSel{
    NSString *getSel = [NSString stringWithFormat:@"%@",self];
    return NSSelectorFromString(getSel);
}

/*判断是否为中文姓名*/
- (BOOL)isValidName{
    NSString *stricterFilterString = @"(^[\u4e00-\u9fa5]{1,6}$)";
    
    NSPredicate *test = [NSPredicate predicateWithFormat:@"SELF MATCHES %@", stricterFilterString];
    return [test evaluateWithObject:self];
}

///*判断输入的是否是手机号码*/
//-(BOOL)isMobileNumber {
//    
//    return [self isMobile];
//}

// 固定电话格式 + 手机号码
- (BOOL)isTelephone {
    NSString * PHS = @"^0(10|2[0-5789]|\\d{3})\\d{7,8}$";
    NSPredicate *regextestmobile = [NSPredicate predicateWithFormat:@"SELF MATCHES %@", PHS];
    
    return [regextestmobile evaluateWithObject:self] || [self isValidPhone];
}

-(BOOL)isValidPhone {
    NSString *stricterFilterString = @"\\b(1)[0-9][0-9][0-9][0-9][0-9][0-9][0-9][0-9][0-9][0-9]\\b";
    NSPredicate *emailTest = [NSPredicate predicateWithFormat:@"SELF MATCHES %@", stricterFilterString];
    return [emailTest evaluateWithObject:self];
}

//- (BOOL)isMobile {
//    
//    // 手机号码
//    // 移动：134[0-8],135,136,137,138,139,150,151,157,158,159,182,187,188
//    // 联通：130,131,132,152,155,156,185,186
//    // 电信：133,1349,153,180,189
//    // 170 添加17号段
//    
//    // ^(1(2|3|4|5|6|7|8|9)[0-9])\\d{8}$
//    // NSString *MOBILE = @"^1(3[0-9]|5[0-35-9]|8[025-9]|7[0-9])\\d{8}$";
//    
//    NSString *MOBILE = @"^(1(2|3|4|5|6|7|8|9)[0-9])\\d{8}$";
//    NSPredicate *regextestmobile = [NSPredicate predicateWithFormat:@"SELF MATCHES %@", MOBILE];
//
//    return [regextestmobile evaluateWithObject:self];
//}

/*判断输入的是否是身份证号码*/
- (BOOL)isValidIdCard{
    NSString *value  = [self stringByTrimmingCharactersInSet:[NSCharacterSet whitespaceAndNewlineCharacterSet]];
    long length = 0;
    if (!value) {
        return NO;
    }else {
        length = value.length;
        if (length !=15 && length !=18) {
            return NO;
        }
    }
    // 省份代码
    NSArray *areasArray =@[@"11",@"12", @"13",@"14", @"15",@"21", @"22",@"23", @"31",@"32", @"33",@"34", @"35",@"36", @"37",@"41",@"42",@"43", @"44",@"45", @"46",@"50", @"51",@"52", @"53",@"54", @"61",@"62", @"63",@"64", @"65",@"71", @"81",@"82", @"91"];
    NSString *valueStart2 = [value substringToIndex:2];
    BOOL areaFlag = NO;
    for (NSString *areaCode in areasArray) {
        if ([areaCode isEqualToString:valueStart2]) {
            areaFlag = YES;
            break;
        }
    }

    if (!areaFlag) {
        return NO;
    }
    
    
    NSRegularExpression *regularExpression;
    NSUInteger numberofMatch;
    
    int year =0;
    switch (length) {
        case 15:
            year = [value substringWithRange:NSMakeRange(6,2)].intValue +1900;
            if (year %4 ==0 || (year %100 ==0 && year %4 ==0)) {
                regularExpression = [[NSRegularExpression alloc] initWithPattern:@"^[1-9][0-9]{5}[0-9]{2}((01|03|05|07|08|10|12)(0[1-9]|[1-2][0-9]|3[0-1])|(04|06|09|11)(0[1-9]|[1-2][0-9]|30)|02(0[1-9]|[1-2][0-9]))[0-9]{3}$"
                                                                         options:NSRegularExpressionCaseInsensitive
                                                                           error:nil];//测试出生日期的合法性
            }else {
                regularExpression = [[NSRegularExpression alloc]initWithPattern:@"^[1-9][0-9]{5}[0-9]{2}((01|03|05|07|08|10|12)(0[1-9]|[1-2][0-9]|3[0-1])|(04|06|09|11)(0[1-9]|[1-2][0-9]|30)|02(0[1-9]|1[0-9]|2[0-8]))[0-9]{3}$"
                                                                       options:NSRegularExpressionCaseInsensitive
                                                                         error:nil];//测试出生日期的合法性
            }
            
            numberofMatch = [regularExpression numberOfMatchesInString:value
                                                              options:NSMatchingReportProgress
                                                                range:NSMakeRange(0, value.length)];
            
            if(numberofMatch >0) {
                return YES;
            }else {
                return NO;
            }
            
        case 18:
            year = [value substringWithRange:NSMakeRange(6,4)].intValue;
            if (year %4 ==0 || (year %100 ==0 && year %4 ==0)) {
                regularExpression = [[NSRegularExpression alloc]initWithPattern:@"^[1-9][0-9]{5}19[0-9]{2}((01|03|05|07|08|10|12)(0[1-9]|[1-2][0-9]|3[0-1])|(04|06|09|11)(0[1-9]|[1-2][0-9]|30)|02(0[1-9]|[1-2][0-9]))[0-9]{3}[0-9Xx]$"
                                                                       options:NSRegularExpressionCaseInsensitive
                                                                         error:nil];//测试出生日期的合法性
            }else {
                regularExpression = [[NSRegularExpression alloc]initWithPattern:@"^[1-9][0-9]{5}19[0-9]{2}((01|03|05|07|08|10|12)(0[1-9]|[1-2][0-9]|3[0-1])|(04|06|09|11)(0[1-9]|[1-2][0-9]|30)|02(0[1-9]|1[0-9]|2[0-8]))[0-9]{3}[0-9Xx]$"
                                                                       options:NSRegularExpressionCaseInsensitive
                                                                         error:nil];//测试出生日期的合法性
            }
            
            numberofMatch = [regularExpression numberOfMatchesInString:value
                                                              options:NSMatchingReportProgress
                                                                range:NSMakeRange(0, value.length)];
            
            if(numberofMatch >0) {
                int S = ([value substringWithRange:NSMakeRange(0,1)].intValue +
                         [value substringWithRange:NSMakeRange(10,1)].intValue) *7 +
                         ([value substringWithRange:NSMakeRange(1,1)].intValue +
                          [value substringWithRange:NSMakeRange(11,1)].intValue) *9 +
                          ([value substringWithRange:NSMakeRange(2,1)].intValue +
                           [value substringWithRange:NSMakeRange(12,1)].intValue) *10 +
                           ([value substringWithRange:NSMakeRange(3,1)].intValue +
                            [value substringWithRange:NSMakeRange(13,1)].intValue) *5 +
                            ([value substringWithRange:NSMakeRange(4,1)].intValue +
                             [value substringWithRange:NSMakeRange(14,1)].intValue) *8 +
                             ([value substringWithRange:NSMakeRange(5,1)].intValue +
                              [value substringWithRange:NSMakeRange(15,1)].intValue) *4 +
                              ([value substringWithRange:NSMakeRange(6,1)].intValue +
                               [value substringWithRange:NSMakeRange(16,1)].intValue) *2 +
                               [value substringWithRange:NSMakeRange(7,1)].intValue *1 +
                               [value substringWithRange:NSMakeRange(8,1)].intValue *6 +
                               [value substringWithRange:NSMakeRange(9,1)].intValue *3;
                
                int Y = S %11;
                NSString *M =@"F";
                NSString *JYM =@"10X98765432";
                
                M = [JYM substringWithRange:NSMakeRange(Y,1)];// 判断校验位
                if ([M isEqualToString:@"X"]) {
                }
                if ([M isEqualToString:[value substringWithRange:NSMakeRange(17,1)]]) {
                    return YES;// 检测ID的校验位
                }else if([M isEqualToString:@"X"]&&
                         [[value substringWithRange:NSMakeRange(17,1)] isEqualToString:@"x"]){
                    return YES;//当x写成小写的时候也能通过
                }else {
                    return NO;
                }
                
            }else {
                return NO;
            }
        default:
            return NO;
    }
}

/*判断输入帐号是否为邮箱*/
-(BOOL)isValidEmail
{
    NSString *stricterFilterString = @"[A-Z0-9a-z._%+-]+@[A-Za-z0-9.-]+\\.[A-Za-z]{2,4}";
    NSString *laxString = @".+@.+\\.[A-Za-z]{2}[A-Za-z]";
    NSString *emailRegex = stricterFilterString ? stricterFilterString : laxString;
    NSPredicate *emailTest = [NSPredicate predicateWithFormat:@"SELF MATCHES %@", emailRegex];
    return [emailTest evaluateWithObject:self];
}

/*判断昵称只能是中英文、数字、下划线*/
-(BOOL)isValidNickName
{
    NSString *stricterFilterString =@"^[\u4e00-\u9fa5a-zA-Z0-9_]{1,19}$";
    NSPredicate *mtNickNameTest = [NSPredicate predicateWithFormat:@"SELF MATCHES %@", stricterFilterString];
    return [mtNickNameTest evaluateWithObject:self];
}

/*帐号密码格式*/
-(BOOL)isValidPassword
{
    NSString *stricterFilterString = @"^[A-Za-z0-9!@#$%^&*.~/{}|()'\"?><,.`+-=_:;\\\\[]]\\\[]{6,16}$";
    //    NSLog(@"stricterFilterString = %@",stricterFilterString);
    NSPredicate *passwordTest = [NSPredicate predicateWithFormat:@"SELF MATCHES %@", stricterFilterString];
    return [passwordTest evaluateWithObject:self];
}

/*判断是否有效的整数*/
-(BOOL)isValidInteger {
    NSString *stricterFilterString = @"^\\d+$";
    NSPredicate *integerTest = [NSPredicate predicateWithFormat:@"SELF MATCHES %@", stricterFilterString];
    return [integerTest evaluateWithObject:self];
}

/*判断是否有效的正整数*/
-(BOOL)isValidPositiveInteger {
    NSString *stricterFilterString = @"^[0-9]*[1-9][0-9]*$";
    NSPredicate *integerTest = [NSPredicate predicateWithFormat:@"SELF MATCHES %@", stricterFilterString];
    return [integerTest evaluateWithObject:self];
}

/*判断是否有效的浮点数*/
- (BOOL)isValidFloat {
    NSString *stricterFilterString = @"^(\\d*\\.)?\\d+$";
    NSPredicate *floatTest = [NSPredicate predicateWithFormat:@"SELF MATCHES %@", stricterFilterString];
    return [floatTest evaluateWithObject:self];
}

/*判断是否有效的正浮点数*/
- (BOOL)isValidPositiveFloat {
    NSString *stricterFilterString = @"^(([0-9]+\\.[0-9]*[1-9][0-9]*)|([0-9]*[1-9][0-9]*\\.[0-9]+)|([0-9]*[1-9][0-9]*))$";
                                        
    NSPredicate *test = [NSPredicate predicateWithFormat:@"SELF MATCHES %@", stricterFilterString];
    return [test evaluateWithObject:self];
}

/*判断是否为空字符串*/
- (BOOL)isEmpty {
    NSString *stricterFilterString = @"^\[ \t]*$";
    NSPredicate *emptyTest = [NSPredicate predicateWithFormat:@"SELF MATCHES %@", stricterFilterString];
    return [emptyTest evaluateWithObject:self];
}

/*判断是否为中文字符*/
- (BOOL)isValidChinese {
    NSString *stricterFilterString = @"(^[\u4e00-\u9fa5]+$)";
    
    NSPredicate *test = [NSPredicate predicateWithFormat:@"SELF MATCHES %@", stricterFilterString];
    return [test evaluateWithObject:self];
}

/*去除电话号码中的特殊字符*/
- (NSString*)extractNumber{
    NSCharacterSet *doNotWant = [NSCharacterSet characterSetWithCharactersInString:@" @／：；（）¥「」、[]{}#%-*+=_\\|~＜＞$€^•’@#$%^&*()_+’\\”"];
    NSString *trimmedString = [[[self componentsSeparatedByCharactersInSet:doNotWant]componentsJoinedByString: @""] stringByReplacingOccurrencesOfString:@" " withString:@""];
    return trimmedString;
}



- (NSInteger)lengthOfStringCN
{
    NSInteger strlength = 0;
    char* p = (char*)[self cStringUsingEncoding:NSUnicodeStringEncoding];
    for (NSUInteger i=0 ; i<[self lengthOfBytesUsingEncoding:NSUnicodeStringEncoding] ;i++) {
        if (*p) {
            p++;
            strlength++;
        }
        else {
            p++;
        }
        
    }
    return strlength;
}

+ (NSString*)setValueBaseOnDataTypeFromServer:(id)serverData
{
    NSString *saveValueStr = nil;
    if ([serverData isKindOfClass:[NSNumber class]]) {
        
        saveValueStr = [NSString stringWithFormat:@"%d",[((NSNumber*)serverData) intValue]];
    } else {
        
        saveValueStr = serverData;
    }
    
    return saveValueStr;
}

+ (NSString*)setNilStrToEmptyStr:(NSString*)str
{
    if (str == nil) {
        
        str = @"";
        
    }
    return str;
}

//判断是否有中文
+(BOOL)isChinese:(NSString *)str {
    for(int i=0; i< [str length];i++){
        int a = [str characterAtIndex:i];
        if( a > 0x4e00 && a < 0x9fff)
        {
            return YES;
        }
        
    }
    return NO;
}


+(NSInteger)lenOfChinese:(NSString *)str
{
    NSInteger hanzNUm = 0;
    if (nil == str){
        return hanzNUm;
    }
    
    for(int i=0; i< [str length];i++){
        
        int a = [str characterAtIndex:i];
        
        if( a > 0x4e00 && a < 0x9fff){
            
            hanzNUm++;
        }
    }
    
    return hanzNUm;
}

+(NSInteger)lenOfCharacter:(NSString *)str
{
    
    NSInteger otherNUm = 0;
    
    if (nil == str){
        return otherNUm;
    }
    
    for(int i=0; i< [str length];i++){
        
        int a = [str characterAtIndex:i];
        
        if((a >= 'A' && a<= 'Z') || (a >= 'a' && a <='z')){
            otherNUm++;
        }
        
    }
    
    return otherNUm;
    
}

//- (void)textFiledEditChanged:(NSNotification *)obj{
//    
//    UITextField *textField = (UITextField *)obj.object;
//    
//    NSString *toBeString = textField.text;
//    
//    NSString *lang = [[UITextInputMode currentInputMode] primaryLanguage]; // 键盘输入模式
//    
//    if ([lang isEqualToString:@"zh-Hans"]) { // 简体中文输入，包括简体拼音，健体五笔，简体手写
//        
//        UITextRange *selectedRange = [textField markedTextRange];
//        
//        //获取高亮部分
//        
//        UITextPosition *position = [textField positionFromPosition:selectedRange.start offset:0];
//        
//        // 没有高亮选择的字，则对已输入的文字进行字数统计和限制
//        
//        if (!position) {
//            
//            NSString *str = textField.text;
//            
//            int hanzNUm=0;
//            
//            int otherNUm=0;
//            
//            for(int i=0; i< [str length];i++){
//                
//                int a = [str characterAtIndex:i];
//                
//                if( a > 0x4e00 && a < 0x9fff){
//                    
//                    hanzNUm++;
//                    
//                }else if((a >= 'A' && a <= 'Z') || (a >= 'a' && a <='z')){
//                    
//                    otherNUm++;
//                }
//                
//            }
//            
//            int max = 0;//代表剩余可以输入的字符
//            
//            if (otherNUm == 0){//英文输入
//                
//                max = 4;
//                
//            } else if (hanzNUm == 0){//中文输入
//                
//                max = 8;
//                
//            } else {//英文加汉字混和输入
//                
//                max = 6;
//            }
//            
//            if (toBeString.length > max) {
//                
//                textField.text = [toBeString substringToIndex:max];
//                
//            }
//            
//        }
//        
//        // 有高亮选择的字符串，则暂不对文字进行统计和限制
//        
//        else{
//            
//        }
//        
//    }
//    
//    // 中文输入法以外的直接对其统计限制即可，不考虑其他语种情况
//    
//    else{
//        
//        NSString *str = textField.text;
//        
//        int hanzNUm = 0;
//        
//        int otherNUm = 0;
//        
//        for(int i = 0; i < [str length];i++){
//            
//            int a = [str characterAtIndex:i];
//            
//            if( a > 0x4e00 && a < 0x9fff) {//中文个数
//                
//                hanzNUm++;
//                
//            } else if ((a >= 'A' && a <= 'Z') || (a >= 'a' && a <='z')) {//英文个数
//                
//                otherNUm++;
//            }
//        }
//        
//        int max=0;
//        
//        if (otherNUm == 0){
//            
//            max = 4;
//            
//        } else if(hanzNUm==0){
//            
//            max = 8;
//            
//        }else{
//            
//            max = 6;
//        }
//        
//        
//        if (toBeString.length > max) {
//            textField.text = [toBeString substringToIndex:max];
//        }
//    }
//    
//}


+(NSString *)MD5WithString:(NSString *)string{
    const char *cStr = [string UTF8String];
    unsigned char result[16];
    CC_MD5( cStr, (CC_LONG)strlen(cStr), result );
    return [NSString stringWithFormat:
            @"%02x%02x%02x%02x%02x%02x%02x%02x%02x%02x%02x%02x%02x%02x%02x%02x",
            result[0], result[1], result[2], result[3],
            result[4], result[5], result[6], result[7],
            result[8], result[9], result[10], result[11],
            result[12], result[13], result[14], result[15]
            ];
    
}

- (BOOL)isValidShopShortName{
    if(self.length < 5 || self.length > 25)
        return NO;
    else
        return YES;
}

- (BOOL)isValidPersonName{
    if(self.length < 2 || self.length > 6)
        return NO;
    else
        return YES;
    
}

- (BOOL)isValideAddress{
    if(self.length < 5 || self.length > 35)
        return NO;
    else
        return YES;
    
}

- (BOOL)isValideLicenceNO{
    return self.length == 15 && [self isValidPositiveInteger];
}


@end
